package com.ktjiaoyu.crm.service.impl;

import com.ktjiaoyu.crm.pojo.Role;
import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.mapper.UserMapper;
import com.ktjiaoyu.crm.service.UserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public User login(String usrName, String usrPassword) {
        return userMapper.findByUsrNameAndUsrPassword(usrName,usrPassword).get(0);
    }

    @Override
    public void saveUser(User user) {
        userMapper.save(user);
    }

    @Override
    public void deleteUser(Long usrId) {
        userMapper.deleteById(usrId);
    }

    @Override
    @Cacheable(value = "user",keyGenerator = "keyGenerator")
    public User getUser(Long usrId) {
        return userMapper.findById(usrId).get();
    }

    @Override
    public Page<User> findUsers(String usrName, Long roleId, Pageable pageable) {
        Specification<User> specification=new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates=new ArrayList<>();
                if(usrName!=null&& !usrName.equals("")){
                    predicates.add(criteriaBuilder.like(root.get("usrName"),"%"+usrName+"%"));
                }
                
                if(roleId!=null&&roleId.longValue()!=0){
                    Role role=new Role();
                    role.setRoleId(roleId);
                    predicates.add(criteriaBuilder.equal(root.get("role"),role));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return userMapper.findAll(specification,pageable);
    }

    @Override
    public User getUserByUsrName(String usrName) {
        return userMapper.findUserByUsrName(usrName);
    }

    @Override
    public String encryptPassword(Object plaintextPassword) throws IllegalArgumentException {
        String salt="czkt";
        Md5Hash md5Hash=new Md5Hash(plaintextPassword,salt,2);
        return md5Hash.toString();
    }
}
